package com.eshin.amqpconfig;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Binding.DestinationType;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;


@Configuration
@AutoConfigureBefore(ConnectionFactory.class)
@EnableConfigurationProperties(RabbitmqProperties.class)
public class DeclaredConfiguration {
 
	@Autowired
	RabbitmqProperties rabbitmqProperties;
	
	@PostConstruct
	public void initDeclared(){
		List<ConnetctionConfig>connects = rabbitmqProperties.getConnect();
		List<DeclaredProperties>declaredProperties = rabbitmqProperties.getBinders();
		String username = rabbitmqProperties.getUsername();
		String password = rabbitmqProperties.getPassword();
		for(ConnetctionConfig connect:connects){
			CachingConnectionFactory connectFactory = new CachingConnectionFactory();
			connectFactory.setHost(connect.getHost());
			connectFactory.setPort(connect.getPort());
			connectFactory.setUsername(username);
			connectFactory.setPassword(password);
			AmqpAdmin amqpAdmin = new RabbitAdmin(connectFactory);
			try {
				Connection con = connectFactory.createConnection();
				if(null != con){
					declared(declaredProperties,amqpAdmin);
				}
			} catch (AmqpException e) {
				System.out.println("unreachable rabbitmq server:"+connectFactory.getHost()+":"+connectFactory.getPort());
			}
			
			
		}
		
	}

	public void declared(List<DeclaredProperties> declaredProperties, AmqpAdmin amqpAdmin) {

		String exchanger = null;
		String queue = null;
		String binding = null;
		for(DeclaredProperties declared:declaredProperties){
			exchanger = declared.getExchange();
			queue = declared.getQueue();
			binding = declared.getRoutingKey();
			if(!StringUtils.isEmpty(exchanger)){
				amqpAdmin.declareExchange(new TopicExchange(exchanger));
			}
			if(!StringUtils.isEmpty(queue)){
				amqpAdmin.declareQueue(new Queue(queue));
			}
			if(!(StringUtils.isEmpty(exchanger)|| StringUtils.isEmpty(queue)
					|| StringUtils.isEmpty(binding))){
				amqpAdmin.declareBinding(new Binding(queue, DestinationType.QUEUE, exchanger, binding, null));
			}
		}
	}
}
